package com.far;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.microedition.khronos.opengles.GL10;


public class Mesh {

	//Buffers
	private FloatBuffer vertexBuffer = null;
	private ShortBuffer indexBuffer = null;
	private FloatBuffer colourBuffer = null;
	
	private int numberOfIndices = -1;
	
	//Default Colour
	private final float[] rgba = new float[] {Utils.DEFAULT_RED, Utils.DEFAULT_GREEN, Utils.DEFAULT_BLUE, Utils.DEFAULT_ALPHA};

	//Positional Params
	private float x = 0;
	private float y = 0;
	private float z = 0;
	
	//Rotation Params
	private float rx = 0;
	private float ry = 0;
	private float rz = 0;
	
	public void draw(GL10 gl){
		
		gl.glFrontFace(GL10.GL_CCW);
		gl.glEnable(GL10.GL_CULL_FACE);
		gl.glCullFace(GL10.GL_BACK);
		
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
		
		gl.glColor4f(rgba[0], rgba[1], rgba[2], rgba[3]);
		
		if(colourBuffer != null){
			gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
			gl.glColorPointer(4, GL10.GL_FLOAT, 0, colourBuffer);
		}
		
		gl.glTranslatef(x, y, z);
		gl.glRotatef(rx, 1, 0, 0);
		gl.glRotatef(ry, 0, 1, 0);
		gl.glRotatef(rz, 0, 0, 1);
		
		gl.glDrawElements(GL10.GL_TRIANGLES, numberOfIndices, GL10.GL_UNSIGNED_SHORT, indexBuffer);
		
		if(colourBuffer != null){
			gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		}
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);

		gl.glDisable(GL10.GL_CULL_FACE);
		
	}
	
	protected void setVertices(float[] vertices){
		ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
		vbb.order(ByteOrder.nativeOrder());
		vertexBuffer = vbb.asFloatBuffer();
		vertexBuffer.put(vertices);
		vertexBuffer.position(0);
	}
	
	protected void setIndices(short[] indices){
		ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
		ibb.order(ByteOrder.nativeOrder());
		indexBuffer = ibb.asShortBuffer();
		indexBuffer.put(indices);
		indexBuffer.position(0);
		
		numberOfIndices = indices.length;
	}
	
	protected void setColour(float red, float green, float blue, float alpha){
		rgba[0] = red;
		rgba[1] = green;
		rgba[2] = blue;
		rgba[3] = alpha;
	}
	
	protected void setColours(float[] topLeft, float[] bottomLeft, float[] bottomRight, float[] topRight){
		float[] colours = {};
		colours = Utils.mergeFloatArrays(colours, topLeft);
		colours = Utils.mergeFloatArrays(colours, bottomLeft);
		colours = Utils.mergeFloatArrays(colours, bottomRight);
		colours = Utils.mergeFloatArrays(colours, topRight);
		
		ByteBuffer cbb = ByteBuffer.allocateDirect(4 * topLeft.length * 4);
		cbb.order(ByteOrder.nativeOrder());
		colourBuffer = cbb.asFloatBuffer();
		colourBuffer.put(colours);
		colourBuffer.position(0);
	}

}
